package com.disktalk.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * org.jivesoftware.spark.remotecontrol.utils
 * 作者      : 陈晓
 * 描述      : 获得本机的Ip地址
 * 创建日期  : 2017/6/23
 * 修改日期  :
 */
public class GetIpAddress {

    private static String ipAddress;
    private static final Pattern IPV4_PATTERN =
            Pattern.compile(
                    "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");

    /**
     * 用于获得本地的ip地址
     *
     * @return 返回本地的Ip地址
     * @throws Exception
     */
    public static InetAddress getLocalHostLANAddress() throws Exception {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    //System.out.println(inetAddr.getHostAddress());
                    if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddr;
                        } else if (candidateAddress == null && !inetAddr.isLinkLocalAddress()) {//不拿IPv6的ip地址
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            return jdkSuppliedAddress;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断获取的IP是否存在字符串
     *
     * @param str ip
     * @return
     */
    public static boolean isExistStr(String str) {
        Pattern pattern = Pattern.compile("[a-zA-Z]|\\d|[\u4E00-\u9FA5]");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            // 如匹配成功即走到这里
            System.out.println("88888：" + matcher.group());
            return true;
        }
        return false;
    }

    /**
     * 获取Ip地址
     *
     * @return ip地址
     */
    public static String getLocalIp() {
        try {
            InetAddress localHostLANAddress = getLocalHostLANAddress();
            ipAddress = localHostLANAddress.getHostAddress();
            boolean iPv4Address = isIPv4Address(ipAddress);
            // System.out.println(iPv4Address+"====");
            // System.out.println("99==99:"+InetAddress.getLocalHost().getHostAddress());
            if(!iPv4Address){
                ipAddress = InetAddress.getLocalHost().getHostAddress();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ipAddress;
    }

    /**
     * 用正则表达式判断获得的ip地址是否属于IpV4
     * @param input
     * @return boolean
     */
    public static boolean isIPv4Address(final String input) {
        return IPV4_PATTERN.matcher(input).matches();
    }

    public static void main(String[] args) throws Exception {
        String hostAddress = getLocalHostLANAddress().getHostAddress();
        String localIp = getLocalIp();
        System.out.println("999999999:" + localIp);
        System.out.println("66666666:" + hostAddress);
    }
}
